<template>
  <el-dialog :visible.sync="dialog" :title="isAdd ? '新增用户' : '编辑用户'" append-to-body width="570px" :close-on-click-modal="false">
    <el-form ref="form" :inline="false" :model="form" :rules="rules" size="small" label-width="66px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户名" prop="userName">
            <el-input v-model="form.userName"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="显示名" prop="realname">
            <el-input v-model="form.realname"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="状态" prop="state">
        <el-radio v-for="item in dicts" :key="item.id" v-model="form.state" :label="item.value">{{ item.label }}</el-radio>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="电话" prop="telephone">
            <el-input v-model.number="form.telephone" :readonly="isAdd == false"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="部门">
        <treeselect v-model="deptId" :options="depts" :style="style" placeholder="选择部门" :default-expand-level="2" @select="selectFun"/>
      </el-form-item>
      <el-form-item label="岗位">
        <treeselect v-model="roleIds" :options="roles" style="width: 450px" placeholder="选择岗位" 
        :multiple="true" :disable-branch-nodes="true" :show-count="true" :default-expand-level="2"/>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="cancel">取消</el-button>
      <el-button :loading="loading" type="primary" @click="doSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>

import { add, edit } from '@/api/user'
import { getDepts } from '@/api/dept'
import { getTree, getLevel } from '@/api/role'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
  components: { Treeselect },
  props: {
    isAdd: {
      type: Boolean,
      required: true
    },
    sup_this: {
      type: Object,
      default: null
    },
    dicts: {
      type: Array,
      required: true
    }
  },
  data() {
    const validtelephone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入电话号码'))
      } else if (!this.isValidTelephone(value)) {
        callback(new Error('请输入正确的11位手机号码'))
      } else {
        callback()
      }
    }
    return {
      dialog: false,
      loading: false,
      form: { 
        userName: '', 
        email: '', 
        state: 'false', 
        roles: [], 
        job: { id: '' }, 
        dept: { id: '' }, 
        telephone: null 
      },
      roleIds: [], 
      roles: [],
      depts: [], 
      deptId: null, 
      style: 'width: 184px', 
      level: 3,
      rules: {
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        realname: [
          { required: true, message: '请输入显示名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        telephone: [
          { required: true, trigger: 'blur', validator: validtelephone }
        ],
        state: [
          { required: true, message: '状态不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    const explorer = navigator.userAgent
    if (explorer.indexOf('Chrome') >= 0) {
      this.style = 'width: 184px'
    } else {
      this.style = 'width: 172px'
    }
  },
  methods: {
    cancel() {
      this.resetForm()
    },
    doSubmit() {
      this.form.dept.deptId = this.deptId
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.deptId === null || this.deptId === undefined) {
            this.$message({
              message: '部门不能为空',
              type: 'warning'
            })
          } else if (this.roleIds.length === 0) {
            this.$message({
              message: '岗位不能为空',
              type: 'warning'
            })
          } else {
            this.loading = true
            this.form.roles = []
            const _this = this
            this.roleIds.forEach(function(data, index) {
              const role = { merchantRoleId: data }
              _this.form.roles.push(role)
            })
            if (this.isAdd) {
              this.doAdd()
            } else {
              this.doEdit()
            }
          }
        } else {
          return false
        }
      })
    },
    doAdd() {
      add(this.form).then(res => {
        this.resetForm()
        this.$message({
          message: '初始密码：123456，请及时修改密码',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.sup_this.init()
      }).catch(err => {
        this.loading = false
        this.$notify({
          title: '添加失败',
          message: err.msg,
          type: 'error'
        })
      })
    },
    doEdit() {
      edit(this.form).then(res => {
        this.resetForm()
        this.$message({
          message: '修改成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.sup_this.init()
      }).catch(err => {
        this.loading = false
        this.$notify({
          title: '添加失败',
          message: err.msg,
          type: 'error'
        })
      })
    },
    resetForm() {
      this.dialog = false
      this.$refs['form'].resetFields()
      this.deptId = null
      this.roleIds = []
      this.form = { userName: '', email: '', state: 'false', roles: [], dept: { deptId: '' }, telephone: null }
    },
    getRoles() {
      getTree().then(res => {
        this.roles = res.data
      }).catch(err => {
        console.log(err.msg)
      })
    },
    getDepts() {
      getDepts({ state: true }).then(res => {
        this.depts = res.data.list
      })
    },
    isValidTelephone(str) {
      const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
      return reg.test(str)
    },
    selectFun(node, instanceId) {

    },
    getRoleLevel() {
      getLevel().then(res => {
        console.log(res)
        this.level = res.data.level
      }).catch(err => {
        console.log(err.msg)
      })
    }
  }
}
</script>

<style scoped>

</style>
